<template>
  <div style="width: 100%;">
    <el-form :inline="true" class="form-inline">
      <el-form-item label="学期">
        <el-select style="width: 200px;" v-model="selectedTerm" placeholder="请选择学期">
          <el-option v-for="term in terms" :key="term.index" :label="term.label" :value="term.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年级">
        <el-select style="width: 200px;" v-model="selectedGrade" placeholder="请选择年级" @change="queryClass">
          <el-option v-for="grade in grades" :key="grade.index" :label="grade.label" :value="grade.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级">
        <el-select style="width: 200px;" v-model="selectedClass" placeholder="请选择班级" @change="queryCoursePlan">
          <el-option v-for="classItem in classes" :key="classItem.index" :label="classItem.label"
            :value="classItem.value"></el-option>
        </el-select>
      </el-form-item>

      <!-- <div style="display: flex; height: 40px">
        <el-button type="primary" @click="judgeLesson" class="addbtn">冲突检测</el-button>
        <h3 style="line-height: 40px;margin-left: 20px;color: red">(红色-讲师冲突 绿色-班级冲突 黄色-教室冲突)</h3>
      </div> -->
      
    </el-form>

    <div class="timetable">
      <table style="width: 100%;">
        <thead>
          <tr>
            <th style="width: 8%;">时间</th>
            <th v-for="day in days" :key="day">{{ day }}</th>
          </tr>
        </thead>
        <tbody>
          <tr style="height: 70px" v-for="(period, periodIndex) in periods" :key="period">
            <td>{{ period }}</td>
            <td v-for="dayIndex in 5" :key="dayIndex">
              <VueDraggable v-model="timetable[periodIndex]" :group="{ name: 'lessons', pull: true, put: true }"
                :list="timetable[periodIndex]" :sort="false" @end="onDragEnd" :data-periodIndex="periodIndex"
                :data-dayIndex="dayIndex - 1">
                <!-- <div
                  v-if="timetable[periodIndex][dayIndex - 1]"
                  class="lesson"
                >
                  {{ renderLesson(timetable[periodIndex][dayIndex - 1]) }}
                </div> -->
                <div v-if="timetable[periodIndex][dayIndex - 1]"
                  :class="renderLesson(timetable[periodIndex][dayIndex - 1]).class">
                  {{ renderLesson(timetable[periodIndex][dayIndex - 1]).textContent }}
                </div>
              </VueDraggable>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watchEffect } from 'vue';
import { VueDraggable } from 'vue-draggable-plus';

const { proxy } = getCurrentInstance();


const conflictMaps = ref({})

const judgeLesson = async () => {
  // 所有的课程计划列表
  const allLessons = await proxy.$api.getCourseplanall();

  const teacherConflictsMap = new Map(); // 使用Map存储，以时间戳为键，讲师集合为值
  const classConflictsMap = new Map(); // 同上，班级
  const classroomConflictsMap = new Map(); // 同上，教室

  allLessons.forEach((lesson) => {
    const { classTime, teacherNo, classNo, classroomNo } = lesson;

    // 初始化映射中的键值
    if (!teacherConflictsMap.has(classTime)) teacherConflictsMap.set(classTime, new Set());
    if (!classConflictsMap.has(classTime)) classConflictsMap.set(classTime, new Map());
    if (!classroomConflictsMap.has(classTime)) classroomConflictsMap.set(classTime, new Set());

    // 添加到相应的映射中
    teacherConflictsMap.get(classTime).add(teacherNo);
    if (!classConflictsMap.get(classTime).has(classNo)) classConflictsMap.get(classTime).set(classNo, new Set());
    classConflictsMap.get(classTime).get(classNo).add(lesson.id); // 假设lesson.id是唯一的标识符
    classroomConflictsMap.get(classTime).add(classroomNo);
    
  });

  // 统一检查冲突并记录
  for (const [time, teachers] of teacherConflictsMap.entries()) {
    if (teachers.size > 1) {
      // console.log(`冲突发现于时间${time}: 讲师冲突`);
    }
  }

  for (const [time, classes] of classConflictsMap.entries()) {
    for (const [classId, lessons] of classes.entries()) {
      if (lessons.size > 1) {
        // console.log(`冲突发现于时间${time}: 班级${classId}排课冲突`);
      }
    }
  }

  for (const [time, classrooms] of classroomConflictsMap.entries()) {
    if (classrooms.size > 1) {
      // console.log(`冲突发现于时间${time}: 教室冲突`);
    }
  }

  // 更新冲突映射至外部变量
  conflictMaps.value = { teacherConflictsMap, classConflictsMap, classroomConflictsMap };
};

const terms = ref([
  { value: "2019-2020-1", label: "2019-2020-1" },
]);

const grades = ref([
  { value: "01", label: "高一" },
  { value: "02", label: "高二" },
  { value: "03", label: "高三" },
]);
const classes = ref([{ value: "", label: "" }]);
const selectedTerm = ref('');
const selectedGrade = ref('');
const selectedClass = ref('');
const days = ref(['周一', '周二', '周三', '周四', '周五']);
const periods = ref(['第一节', '第二节', '第三节', '第四节', '第五节', '第六节', '第七节', '第八节']);
const lessons = ref([]);

const timetable = ref(Array.from({ length: 8 }, () => Array(5).fill(null)));

const lessonsForDay = () => {
  // console.log("======================lessonsForDay======================");
  // console.log(conflictMaps.value)

  // 按classTime排序
  lessons.value.sort((a, b) => a.classTime - b.classTime);

  // 初始化时间表
  timetable.value = Array.from({ length: 8 }, () => Array(5).fill(null));

  lessons.value.forEach(lesson => {
    const index = parseInt(lesson.classTime) - 1;
    const dayIndex = Math.floor(index / 8);
    const periodIndex = index % 8;
    timetable.value[periodIndex][dayIndex] = lesson;
  });
}


// Cannot destructure property 'classTime' of 'lesson' as it is undefined
const renderLesson = (lesson) => {
  var { classTime, teacherNo, classNo, classroomNo } = lesson;

  // console.log(conflictMaps.value.classConflictsMap);
  // console.log(conflictMaps.value.teacherConflictsMap);
  // console.log(conflictMaps.value.teacherConflictsMap);
  if (conflictMaps.value.classConflictsMap != null || conflictMaps.value.teacherConflictsMap != null || conflictMaps.value.teacherConflictsMap != null) {
    var isTeacherConflict = conflictMaps.value?.teacherConflictsMap[classTime]?.has(teacherNo) ?? false;
    var isClassConflict = conflictMaps.value?.classConflictsMap[classTime]?.get(classNo)?.size > 1 ?? false;
    var isClassroomConflict = conflictMaps.value?.classroomConflictsMap[classTime]?.size > 1 ?? false;
  }

  let conflictClass = '';
  if (isTeacherConflict) conflictClass = 'teacher-conflict';
  else if (isClassConflict) conflictClass = 'class-conflict';
  else if (isClassroomConflict) conflictClass = 'classroom-conflict';

  // return `<div class="lesson ${conflictClass}">${lesson.realname}-${lesson.courseName}(${lesson.classroomNo})</div>`;
  // console.log(conflictClass);
  return {
    class: `lesson ${conflictClass}`,
    // class: `lesson teacher-conflict`,
    // 直接返回文本内容而非innerHTML，更安全且符合Vue数据绑定原则
    textContent: `${lesson.realname}-${lesson.courseName}(${lesson.classroomNo})`
  };
};

const onDragEnd = async (event) => {
  queryCoursePlan();

  const oldperiodIndex = parseInt(event.from.dataset.periodindex);
  const olddayIndex = parseInt(event.from.dataset.dayindex);

  const newperiodIndex = parseInt(event.to.dataset.periodindex);
  const newdayIndex = parseInt(event.to.dataset.dayindex);

  const courseData = await proxy.$api.queryCourseplan(selectedClass.value);
  courseData.sort((a, b) => a.classTime - b.classTime);
  console.log(courseData[oldperiodIndex * olddayIndex + oldperiodIndex]);
  console.log(courseData[newperiodIndex * newdayIndex + newperiodIndex]);

  const oldLesson = courseData[oldperiodIndex * olddayIndex + oldperiodIndex];
  const newLesson = courseData[newperiodIndex * newdayIndex + newperiodIndex]

  //索引值的计算
  if (oldLesson && newLesson) {
    const oldLessonId = oldLesson.id;
    const newLessonId = newLesson.id;

    ElMessageBox.confirm(`你确定要交换课程 ${oldLesson.realname} (${oldLesson.courseName})(${oldLesson.classroomNo}) 和 ${newLesson.realname} (${newLesson.courseName}) (${newLesson.classroomNo}) 吗？`, '确认交换', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'my-messagebox'
    }).then(async () => {
      console.log(`交换课程: ${oldLessonId} <-> ${newLessonId}`);

      await proxy.$api.ManualCoursePlan({
        "oldId": oldLessonId,
        "newId": newLessonId
      });

      ElMessage.success(`交换课程 ${oldLesson.realname} (${oldLesson.courseName})(${oldLesson.classroomNo}) 和 ${newLesson.realname} (${newLesson.courseName}) (${newLesson.classroomNo}) 成功！`);
    }).catch(() => {
      ElMessage.info('取消交换');
    }).finally(() => {
      queryCoursePlan();
    })


  } else {
    ElMessage.error('课程交换失败');
  }
};

// 客户端进行查询班级编号和名称
const queryClass = async () => {
  const result = await proxy.$api.queryClass(selectedGrade.value);
  classes.value.splice(0, classes.value.length);
  selectedClass.value = "";
  result.map((v) => {
    classes.value.push({
      value: v.classNo,
      label: v.className,
    });
  });
};

// 查询课程表
const queryCoursePlan = async () => {
  lessons.value = [];
  const courseData = await proxy.$api.queryCourseplan(selectedClass.value);
  lessons.value = courseData;
  lessonsForDay();
  // ElMessage({ message: "查询成功", type: "success" });
}
</script>

<style>
.form-inline {
  margin-bottom: 20px;
}

.timetable {
  width: 100%;
  border-collapse: collapse;
}

.timetable th,
.timetable td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: center;
}

.lesson {
  /* background-color: #E6E6FA; */
  /* 薰衣草紫 */
  padding: 5px;
  margin: 2px 0;
  cursor: move;
  border-radius: 4px;
}

.timetable th {
  background-color: #f0f0f0;
}

.timetable td {
  height: 50px;
}

.my-messagebox .el-messagebox__body {
  z-index: 3002 !important;
}

.teacher-conflict {
  background-color: #FFCDD2;
  /* 红色，表示讲师冲突 */
}

.class-conflict {
  background-color: #C8E6C9;
  /* 绿色，表示班级冲突 */
}

.classroom-conflict {
  background-color: #FFECB3;
  /* 浅黄色，表示教室冲突 */
}
</style>